// 工单设置 报修来源
import type { tableListDataItemType, formNameAndValueStateType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElLink, ElIcon, ElSpace, ElDialog, ElButton, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import RepairSourceOption from './options/RepairSourceOption'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'RepairSource',
  props: ['repairSourceKey'],

  setup(props: { repairSourceKey: string } = { repairSourceKey: '' }) {
    const store = useStore()

    // 初始值
    const proSaasTableRef = ref<ProSaasTableExposeType>() // 列表
    const allName = ref() // 当前列表里所有名字
    const original = ref('') // 原始编辑时的名
    const delRow = ref<tableListDataItemType>() // 删除的行数据

    const formState = reactive<formNameAndValueStateType>({
      title: '', // 标题
      addOrEditShow: false, // 新增/编辑 弹窗是否显示
      delShow: false, // 删除 弹窗是否显示
      form: {
        cfgTypeName: '', // 报修来源 名
        cfgValue: '', // 处理时长 值
        cfgTypeCode: '', // 传进来的code
        status: 0 // 数据类型
      }
    })

    onMounted(() => {
      getCfgTypeName()
    })

    const columns: TableColumnProps<tableListDataItemType>[] = [
      {
        label: '报修来源',
        prop: 'cfgTypeName',
        minWidth: 180,
        fixed: 'left',
        align: 'center'
      },
      {
        label: '处理时长',
        prop: 'cfgValue',
        minWidth: 180,
        align: 'center',
        render: (_, value) => {
          return <>{value} 小时</>
        }
      },
      {
        label: '数据类型',
        prop: 'status',
        minWidth: 180,
        align: 'center',
        render: (_, value) => <>{value === 0 ? '自定义' : '系统'}</>
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 220,
        fixed: 'right',
        align: 'center',
        render: ({ row }) => {
          return (
            <>
              <ElSpace>
                <ElLink type="primary" onClick={() => editRepairSource(row)}>
                  <AliIcon type="icon-bianji" />
                  &nbsp;&nbsp;编辑
                </ElLink>
                &nbsp;&nbsp;
                {row.status === 0 ? (
                  <ElLink type="primary" onClick={() => delRepairSource(row)}>
                    <AliIcon type="icon-shanchu" />
                    &nbsp;&nbsp;删除
                  </ElLink>
                ) : (
                  <span>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  </span>
                )}
              </ElSpace>
            </>
          )
        }
      }
    ]

    // methods
    // 新增
    const addRepairSource = () => {
      formState.title = '新增工单报修来源管理'
      formState.addOrEditShow = true
    }

    // 编辑
    const editRepairSource = async (row: tableListDataItemType) => {
      formState.title = '编辑工单报修来源管理'
      const res = await store.dispatch('order/GetOrderSetView', { id: row.id })
      if (res?.code === 200) {
        formState.form = res.data
        original.value = res.data.cfgTypeName
      }
      formState.addOrEditShow = true
    }

    // 删除
    const delRepairSource = (row?: tableListDataItemType) => {
      formState.delShow = !formState.delShow
      if (formState.delShow) {
        delRow.value = row
      }
    }

    // 删除 提交
    const delSubmit = async () => {
      const res = await store.dispatch('order/PostOrderSetRemove', delRow.value?.id) // 调删除接口
      if (res?.code === 200) {
        proSaasTableRef.value?.toSearch() // 刷新
        delRepairSource() // 关弹窗
        getCfgTypeName() // 更新当前已存在的列表名
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 获取当前列表里所有名字
    const getCfgTypeName = async () => {
      const params = {
        current: 1,
        size: 1000,
        cfgTypeCode: props.repairSourceKey
      }
      const res = await store.dispatch('order/GetOrderSetList', params)
      if (res?.code === 200) {
        allName.value = []
        res.data.records.map((item: { cfgTypeName: string }) =>
          allName.value.push(item.cfgTypeName)
        )
      }
    }

    // 关闭
    const handleClose = () => {
      formState.form = {
        // 置空
        cfgTypeName: '',
        cfgValue: '',
        cfgTypeCode: ''
      }
      proSaasTableRef.value?.toSearch() // 刷新
      getCfgTypeName() // 更新当前已存在的列表名
      formState.addOrEditShow = false
    }

    return () => (
      <>
        <ElButton class={styles['orderSet-addBtn']} type="primary" onClick={addRepairSource}>
          <ElIcon>
            <Plus />
          </ElIcon>
          &nbsp;&nbsp;新增
        </ElButton>
        <ProSaasTable<tableListDataItemType>
          ref={proSaasTableRef}
          columns={columns}
          searchParams={{ cfgTypeCode: props.repairSourceKey }}
          dispatchType="order/GetOrderSetList" // 工单设置列表
        />

        {/* 新增、编辑 */}
        {formState.addOrEditShow && (
          <RepairSourceOption
            visible={formState.addOrEditShow}
            title={formState.title}
            record={formState.form}
            original={original.value}
            allName={allName.value}
            repairSourceKey={props.repairSourceKey}
            onCancel={() => handleClose()}
          />
        )}

        {/* 删除 */}
        <ElDialog
          title="确认删除"
          modelValue={formState.delShow!}
          append-to-body
          width="22%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={() => delRepairSource()}
        >
          <div class={styles['orderSet-content']}>
            <div class={styles['orderSet-largeFont']}>确认删除{delRow.value?.cfgTypeName}</div>
            <div class={styles['orderSet-grayFont']}>删除后不可恢复，是否确认删除。</div>
          </div>
          <div class={styles['confirm-button']}>
            <ElButton
              class={styles['confirm-button-cancel']}
              plain
              onClick={() => delRepairSource()}
            >
              取 消
            </ElButton>
            <ElButton class={styles['confirm-button-submit']} type="primary" onClick={delSubmit}>
              确 定
            </ElButton>
          </div>
        </ElDialog>
      </>
    )
  }
})
